package top.majuan.springboot3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.majuan.springboot3.base.PageBean;
import top.majuan.springboot3.base.R;
import top.majuan.springboot3.dao.TbGamepublisherMapper;
import top.majuan.springboot3.entity.TbGamepublisher;
import top.majuan.springboot3.service.TbGamepublisherService;
import top.majuan.springboot3.vo.PageVo;

import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class TbGamepublisherServiceImpl implements TbGamepublisherService {
    public final TbGamepublisherMapper tbGamepublisherMapper;

    public TbGamepublisher queryBypublisher(String publisher) {
        QueryWrapper<TbGamepublisher> wrapper = new QueryWrapper<>();
        wrapper.eq("publisher",publisher);
        TbGamepublisher tbGamepublisher = tbGamepublisherMapper.selectOne(wrapper);
        return tbGamepublisher;
    }

    @Override
    public R<String> insert(TbGamepublisher tbGamepublisher) {
        TbGamepublisher check = queryBypublisher((tbGamepublisher.getPublisher()));
        if(check!=null){
            return R.fail("游戏发行商已存在",null);
        }
        int i = tbGamepublisherMapper.insert(tbGamepublisher);
        return i==1?R.ok("新增成功",null):R.fail("新增失败",null);
    }

    @Override
    public R<PageVo<TbGamepublisher>> queryPage(PageBean pageBean, TbGamepublisher tbGamepublisher) {
        IPage<TbGamepublisher> page = new Page<>(pageBean.getPageNumber(),pageBean.getPageSize());
        QueryWrapper<TbGamepublisher> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.hasText(tbGamepublisher.getPublisher()),"publisher",tbGamepublisher.getPublisher());
        page = tbGamepublisherMapper.selectPage(page,wrapper);

        return R.ok(page);
    }

    @Override
    public R<TbGamepublisher> queryByid(Integer id) {
        TbGamepublisher tbGamepublisher = tbGamepublisherMapper.selectById(id);
        return tbGamepublisher == null?R.fail("查询失败",null) : R.ok(tbGamepublisher);
    }

    @Override
    public R<String> update(TbGamepublisher tbGamepublisher) {
        TbGamepublisher check = queryBypublisher((tbGamepublisher.getPublisher()));
        if(check!=null && !check.getId().equals(tbGamepublisher.getId())){
            return R.fail("游戏发行商已存在",null);
        }
        int i = tbGamepublisherMapper.updateById(tbGamepublisher);
        return i==1?R.ok("修改成功",null):R.fail("修改失败",null);
    }

    @Override
    public R<String> delete(Integer id) {
        int i = tbGamepublisherMapper.deleteById(id);
        return i==1?R.ok("删除成功",null):R.fail("删除失败",null);
    }
}
